package cn.buk.qms.web;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.tms.dto.AuthInfo;
import cn.buk.tms.entity.bill.ReceiptHistory;
import cn.buk.tms.entity.bill.ReceiptInfo;
import cn.buk.tms.sc.SearchReceiptCriteria;
import cn.buk.tms.bill.service.ReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 *
 * @author yfdai
 * @date 2017-7-18
 */
@RestController
public class ReceiptController extends BaseController {

    @Autowired
    private ReceiptService service;

    /**
     * 创建收款单
     */
    @RequestMapping("/createReceipt.do")
    public JsonResult createReceipt(HttpServletRequest request,
                                    @RequestParam("customerId") int customerId,
                                    @RequestParam("amount") double amount,
                                    @RequestParam("remark") String remark,
                                    @RequestParam(value = "receiptBank", defaultValue = "") String receiptBank,
                                    @RequestParam(value = "receiptDate", required = false) Date receiptDate,
                                    @RequestParam(value = "receiptIds[]", required = false) Integer[] receiptIds
                                            ) {
        var authInfo = AuthInfo.createAuthInfo(getEnterpriseId(request), getUserId(request), getUsername(request));

        return service.createReceipt(authInfo, customerId, amount, remark, receiptBank, receiptDate, receiptIds);
    }

    /**
     * 查找收款单
     */
    @RequestMapping("/searchReceipts")
    public CommonDto<ReceiptInfo> searchReceipts(HttpServletRequest request,
                                                 @ModelAttribute("sc") SearchReceiptCriteria sc,
                                                 @RequestParam(value = "likeCustomerName", required = false) String likeCustomerName) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setLikeCustomerName(likeCustomerName);

        List<ReceiptInfo> tickets = service.searchReceipts(enterpriseId, getUserId(request), sc);

        CommonDto<ReceiptInfo> commonDto = new CommonDto<>();
        commonDto.setDataList(tickets);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 获取收款单详情
     */
    @RequestMapping("/refreshReceiptInfo.do")
    public ReceiptInfo refreshReceiptInfo(HttpServletRequest request,
                                                  @RequestParam("id") int id) {
        final int enterpriseId = getEnterpriseId(request);

        return service.refreshReceiptInfo(enterpriseId, id);
    }

    /**
     * 销账(根据账单）
     */
    @RequestMapping("/writeOffBillInfo.do")
    public JsonResult refreshReceiptInfo(HttpServletRequest request,
                                          @RequestParam("receiptId") int receiptId,
                                          @RequestParam(value = "billId", required = false) Integer billId,
                                          @RequestParam(value = "billNo", required = false) String billNo)  {
        final int enterpriseId = getEnterpriseId(request);
        final String operator = getUsername(request);

        return service.writeOffBillInfo(enterpriseId, operator, receiptId, billId, billNo, false);
    }

    /**
     * 使用（创建）收款单对多张账单进行销账
     */
    @PostMapping("/receipt/{receiptId}/writeOffBills")
    public JsonResult writeOffBillsByReceipt(HttpServletRequest request,
                                            @PathVariable("receiptId") int receiptId,
                                            @RequestParam("customerId") int customerId,
                                            @RequestParam("amount") double amount,
                                            @RequestParam("remark") String remark,
                                            @RequestParam(value = "billIds[]") Integer[] billIds,
                                            @RequestParam(value = "receiptBank", defaultValue = "") String receiptBank,
                                            @RequestParam(value = "receiptDate", required = false) Date receiptDate
    ) {
        var authInfo = AuthInfo.createAuthInfo(getEnterpriseId(request), getUserId(request), getUsername(request));

        try {
            return service.writeOffBillsByReceipt(authInfo, customerId, billIds, receiptId, amount, remark, receiptBank, receiptDate);
        } catch (Exception ex) {
            return JsonResult.createJsonResult(-100, ex.getMessage());
        }
    }



    /**
     * 撤销销账(根据账单）
     */
    @RequestMapping("/undo/writeOff/bill")
    public JsonResult undoWriteOffBill(HttpServletRequest request,
                                         @RequestParam(value = "billId") int billId,
                                       @RequestParam("remark") String remark)  {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.undoWriteOffBill(enterpriseId, username, billId, remark);
    }

    /**
     * 销账(根据结算单）
     */
    @RequestMapping("/writeOff/settlement")
    public JsonResult writeOffSettlement(HttpServletRequest request,
                                         @RequestParam("receiptId") int receiptId,
                                         @RequestParam("settlementId") int settlementId) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.writeOffSettlement(enterpriseId, username, settlementId, receiptId);
    }

    /**
     * 撤销销账(根据结算单）
     */
    @RequestMapping("/undoWriteOff/settlement")
    public JsonResult undoWriteOffSettlement(HttpServletRequest request,
                                         @RequestParam("settlementId") int settlementId,
                                             @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.undoWriteOffSettlement(enterpriseId, username, settlementId, remark);
    }

    /**
     * 获取收款单操作记录
     */
    @RequestMapping("/receipt/{id}/history")
    public List<ReceiptHistory> searchReceiptHistory(HttpServletRequest request,
                                                     @PathVariable("id") int id
    ) {
        final int enterpriseId = getEnterpriseId(request);

        return service.searchReceiptHistory(enterpriseId, id);
    }

    /**
     * 删除收款单
     * @deprecated 使用 deleteReceiptByRequestDelete 替换
     * 该项方法可于2022-01-01后删除
     */
    @Deprecated
    @RequestMapping("/receipt/{id}/delete")
    public JsonResult deleteReceipt(HttpServletRequest request,
                                                   @PathVariable("id") int id
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.deleteReceipt(enterpriseId, username, id);
    }

    /**
     * 删除收款单
     */
    @DeleteMapping("/receipt/{id}")
    public JsonResult deleteReceiptByRequestDelete(HttpServletRequest request,
                                    @PathVariable("id") int id
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.deleteReceipt(enterpriseId, username, id);
    }

    /**
     * 收款单的部分款项退款
     */
    @RequestMapping("/receipt/{id}/refund")
    public JsonResult refundReceipt(HttpServletRequest request,
                                    @PathVariable("id") int id,
                                    @RequestParam("amount") double amount,
                                    @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.refundReceipt(enterpriseId, username, id, amount, remark);
    }

    /**
     * 修改收款单的备注
     */
    @RequestMapping("/receipt/{id}/remark")
    public JsonResult updateReceiptRemark(HttpServletRequest request,
                                    @PathVariable("id") int id,
                                    @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.updateReceiptRemark(enterpriseId, username, id, remark);
    }

    /**
     * 下载支付宝账户账务明细
     */
    @PostMapping("/receipt/alipayBillAccountLog")
    public JsonResult downloadAlipayBillAccountLog(HttpServletRequest request,
                                          @RequestParam("beginDate") final Date beginDate,
                                          @RequestParam("endDate") final Date endDate
                                                   ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.downloadAlipayBillAccountLog(enterpriseId, username, beginDate, endDate);
    }

    /**
     * 修改收款单的客户
     */
    @PostMapping("/receipt/{id}/customer")
    public JsonResult updateReceiptCustomer(HttpServletRequest request,
                                          @PathVariable("id") int id,
                                          @RequestParam("customerId") int customerId) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return service.updateReceiptCustomer(enterpriseId, username, id, customerId);
    }


    /**
     * 多张收款单合并
     */
    @PostMapping("/receipts/merge")
    public JsonResult mergeReceipts(HttpServletRequest request,
                                             @RequestParam(value = "receiptIds[]") Integer[] receiptIds) {
        var authInfo = AuthInfo.createAuthInfo(getEnterpriseId(request), getUserId(request), getUsername(request));
        return service.mergeReceipts(authInfo, receiptIds);
    }

}
